package com.zclcs.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zclcs.mapper.MenuMapper;
import com.zclcs.mapper.RolePermissionMapper;
import com.zclcs.model.DataRet;
import com.zclcs.model.Menu;
import com.zclcs.model.RolePermission;
import com.zclcs.service.MenuService;

@Service
@Transactional
public class MenuServiceImpl implements MenuService {

	@Autowired
	private MenuMapper menuMapper;

	@Autowired
	private RolePermissionMapper rolePermissionMapper;

	@Override
	public List<Menu> selectMenu(Menu menu) {
		if (menu.getRoleId() == null || "".equals(menu.getRoleId())) {
			menu.setRoleId("0");
		}
		List<Menu> menus = menuMapper.selectMenu(menu.getRoleId(), new QueryWrapper<Menu>().eq("m.parent_id", "0")
				.like(menu.getName() != null && !"".equals(menu.getName()), "name", menu.getName())
				.like(menu.getMenuName() != null && !"".equals(menu.getMenuName()), "menu_name", menu.getMenuName())
				.like(menu.getPermission() != null && !"".equals(menu.getPermission()), "permission",
						menu.getPermission())
				.orderByAsc("m.sort"));
		for (Menu menu2 : menus) {
			selectChildrenMenus(menu2, menu);
		}
		return menus;
	}

	/**
	 * 递归算法取出所有菜单子级
	 * 
	 * @param menu          菜单对象
	 * @param user          用户对象
	 * @param childrenMenus 子菜单集合
	 * @return 该菜单对象的所有菜单子级
	 */
	/**
	 * 
	 * @param menu  父菜单编号
	 * @param menu2 条件对象
	 */
	private void selectChildrenMenus(Menu menu, Menu menu2) {
		List<Menu> selectChildrenMenus = menuMapper.selectMenu(menu2.getRoleId(), new QueryWrapper<Menu>()
				.eq("m.parent_id", menu.getId()).eq(menu2.getType() != null, "type", menu2.getType())
				.like(menu2.getName() != null && !"".equals(menu2.getName()), "name", menu2.getName())
				.like(menu2.getMenuName() != null && !"".equals(menu2.getMenuName()), "menu_name", menu2.getMenuName())
				.like(menu2.getPermission() != null && !"".equals(menu2.getPermission()), "permission",
						menu2.getPermission())
				.orderByAsc("sort"));
		menu.setChildren(selectChildrenMenus);
		for (Menu menu3 : selectChildrenMenus) {
			selectChildrenMenus(menu3, menu2);
		}
	}

	@Override
	public void insertMenu(Menu menu) {
		menuMapper.insert(menu);
	}

	@Override
	public DataRet<Object> deleteMenu(List<String> ids) {
		if (menuMapper.selectIsAdmin(new QueryWrapper<Menu>().in("m.id", ids)) > 0) {
			String[] adminUser = menuMapper.selectAdminMenu(new QueryWrapper<Menu>().in("m.id", ids));
			String jsonString = JSON.toJSONString(adminUser);
			return new DataRet<>(999, "请勿删除以下菜单：" + jsonString);
		}
		List<String> childrenIdList = new ArrayList<String>();
		for (String id : ids) {
			Menu menu = new Menu();
			menu.setId(id);
			deleteChildrenMenus(childrenIdList, menu);
		}
		ids.addAll(childrenIdList);
		int deleteBatchIds = menuMapper.deleteBatchIds(ids);
		rolePermissionMapper.delete(new QueryWrapper<RolePermission>().in("function_id", ids));
		return new DataRet<>("删除成功，删除的记录数：" + deleteBatchIds);
	}

	/**
	 * 递归算法取出所有菜单子级，并删除该菜单的所有子菜单
	 * 
	 * @param id   父菜单的parentId
	 * @param menu 父菜单对象
	 */
	private void deleteChildrenMenus(List<String> ids, Menu menu) {
		List<Menu> selectChildrenMenus = menuMapper.selectList(new QueryWrapper<Menu>().eq("parent_id", menu.getId()));
		for (Menu menu2 : selectChildrenMenus) {
			ids.add(menu2.getId());
			deleteChildrenMenus(ids, menu2);
		}
	}

	@Override
	public void updateMenu(Menu menu) {
		menuMapper.updateById(menu);
	}

	@Override
	public void updateChildrenMenu(Menu menu) {
		if (menu.getType().equals(1)) {
			menuMapper.updateById(menu);
			// updateChildrenMenus(menu.getParentId(), menu);
		} else {
			menuMapper.updateById(menu);
			List<String> ids = new ArrayList<>();
			deleteChildrenMenus(ids, menu);
			if (!CollectionUtils.isEmpty(ids)) {
				deleteMenu(ids);
			}
		}
	}

	/**
	 * 递归算法取出所有菜单子级，并更新所有子菜单的parentId
	 * 
	 * @param id   父菜单的parentId
	 * @param menu 父菜单对象
	 */
	/*
	 * private void updateChildrenMenus(String id, Menu menu) { List<Menu>
	 * selectChildrenMenus = menuMapper.selectList(new
	 * QueryWrapper<Menu>().eq("parentId", menu.getId())); for (Menu menu2 :
	 * selectChildrenMenus) { menu2.setParentId(id); updateMenu(menu2);
	 * updateChildrenMenus(id, menu2); } }
	 */

	@Override
	public Boolean validMenuName(Menu menu) {
		Integer selectCount = menuMapper.selectCount(new QueryWrapper<Menu>().eq("name", menu.getName()));
		if (null != menu.getId() && !"".equals(menu.getId())) {
			Menu menu2 = menuMapper.selectOne(new QueryWrapper<Menu>().eq("id", menu.getId()));
			return (menu.getName().equalsIgnoreCase(menu2.getName())) ? true : (selectCount == 1) ? false : true;
		} else {
			return (selectCount == 1) ? false : true;
		}
	}

	@Override
	public Boolean validMenuPermission(Menu menu) {
		Integer selectCount = menuMapper.selectCount(new QueryWrapper<Menu>().eq("permission", menu.getPermission()));
		if (null != menu.getId() && !"".equals(menu.getId())) {
			Menu menu2 = menuMapper.selectOne(new QueryWrapper<Menu>().eq("id", menu.getId()));
			return (menu.getPermission().equalsIgnoreCase(menu2.getPermission())) ? true
					: (selectCount == 1) ? false : true;
		} else {
			return (selectCount == 1) ? false : true;
		}
	}

	@Override
	public void pickUpRoleMenus(RolePermission rolePermission) {
		rolePermissionMapper.insert(rolePermission);
	}

	@Override
	public void putDownRoleMenus(RolePermission rolePermission) {
		rolePermissionMapper.delete(new QueryWrapper<RolePermission>().eq("role_id", rolePermission.getRoleId())
				.eq("function_id", rolePermission.getFunctionId()));
	}

}
